package lock;

/**
 * @author: li_jian
 * @version: 1.0
 * @date: 2020/6/21 22:50
 * @description： synchronized实现生产者消费者
 */
public class TestProductAndConsumer {

    public static void main(String[] args) {
        Clerk clerk =new Clerk();

        Product product =new Product(clerk);
        Consumer consumer = new Consumer(clerk);

        new Thread(product,"生产者 A").start();
        new Thread(consumer,"消费者 B").start();

        new Thread(product,"生产者 C").start();
        new Thread(consumer,"消费者 D").start();
    }
}

//营业员
class Clerk {
    private int product = 0;

    //进货
    public synchronized void get() {
        while (product >= 1) { //为了避免虚假唤醒问题，应该总是使用在循环中,注意要使用while来判断
            System.out.println("产品已满！");

            try {
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

        System.out.println(Thread.currentThread().getName() + " : " + ++product);
        this.notifyAll();
    }

    //卖货
    public synchronized void sale() {
        while (product <= 0) {
            System.out.println("缺货！");

            try {
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

        System.out.println(Thread.currentThread().getName() + " : " + --product);
        this.notifyAll();
    }
}


class Product implements Runnable {

    private Clerk clerk;

    public Product(Clerk clerk) {
        this.clerk = clerk;
    }

    @Override
    public void run() {
        for (int i = 0; i < 10; i++) {
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

            clerk.get();
        }
    }
}

class Consumer implements Runnable{

    private Clerk clerk;

    public Consumer(Clerk clerk) {
        this.clerk = clerk;
    }

    @Override
    public void run() {
        for (int i = 0; i < 10; i++) {
            clerk.sale();
        }
    }
}
